﻿using System;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web.Routing;
using Nasa8x.Mvc.XmlRouting;

namespace Nasa8x.Babi
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            //routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //routes.MapRoute(
            //    "Default", // Route name
            //    "{controller}/{action}/{id}", // URL with parameters
            //    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            //);

            var _section = (MvcRouteConfigurationSection)ConfigurationManager.GetSection("RouteConfiguration");

            routes.MapRoute(_section);

        }

        private static readonly Regex _REGEX_WWW = new Regex(@"www\.(?<mainDomain>.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            string hostName = Request.Headers["x-forwarded-host"];
            hostName = string.IsNullOrEmpty(hostName) ? Request.Url.Host : hostName;
            Match match = _REGEX_WWW.Match(hostName);
            if (match.Success)
            {
                string mainDomain = match.Groups["mainDomain"].Value;
                var builder = new UriBuilder(Request.Url)
                {
                    Host = mainDomain
                };
                string redirectUrl = builder.Uri.ToString();
                Response.Clear();
                Response.StatusCode = 301;
                Response.StatusDescription = "Moved Permanently";
                Response.AddHeader("Location", redirectUrl);
                Response.End();
            }
        }

        protected void Application_Start()
        {
            //AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
    }
}